import copy
from flask import Blueprint, request, current_app
from flask_json import as_json
from flask_jwt_extended import jwt_required

from .is_staff_user import is_staff_user
from app import db
from app.models import CommonResult, CommonPage, Article, Tag
from app.form.article_form import ArticleForm
from app.auth.auth_decorator import has_role
from app.common.enums import RoleCodeEnum

log = current_app.logger
admin_article = Blueprint('admin_article', __name__, url_prefix='/admin/article')


# 注册蓝图
def register_controller(app):
    app.register_blueprint(admin_article)


# 分页查询
@admin_article.post('/page')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def page():
    data = request.get_json()
    current = 1
    page_size = 10
    query = Article.query
    # 如果传入参数
    if data:
        current = data.get('current') or 1
        page_size = data.get('page_size') or 10
        category_id = data.get('category_id')
        has_type = data.get('has_type')
        title = data.get('title')
        description = data.get('description')
        unclassified = data.get('unclassified')
        # 根据条件筛选数据
        if unclassified:
            query = query.filter(Article.category_id.is_(None))
        if category_id:
            query = query.filter(Article.category_id == category_id)
        if has_type:
            query = query.filter(Article.has_type == has_type)
        if title and title.strip():
            query = query.filter(Article.title.like('%{keyword}%'.format(keyword=title)))
        if description and description.strip():
            query = query.filter(Article.description.like('%{keyword}%'.format(keyword=description)))
    # 分页查询
    page_data = query.paginate(
        page=current,
        per_page=page_size,
        error_out=False
    )
    return CommonResult(data=CommonPage(page_data))


# 获取详情
@admin_article.get('/get/<int:article_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def info(article_id):
    article = Article.query.get(article_id)
    if article is None:
        return CommonResult(code=500, msg='文章不存在')
    return CommonResult(data=article, msg='获取成功')


# 添加文章
@admin_article.post('/add')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def add():
    ArticleForm().api_validate()
    data = request.get_json()
    # 深拷贝tags,然后清除tags，防止添加时使用到传入的id集合
    tags = copy.deepcopy(data.get('tags'))
    data.pop('tags')
    # 填充数据
    record = Article()
    record.__dict__.update(data)
    # 读取传入的标签，保存到文章关联表
    record.tags = [Tag.query.get(tag_id) for tag_id in tags]
    # 保存数据库
    db.session.add(record)
    db.session.commit()
    return CommonResult(data=data, msg='保存成功')


# 修改信息
@admin_article.post('/update')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def update():
    ArticleForm().api_validate()
    data = request.get_json()
    # 查询是否存在
    article = Article.query.get(data.get('id'))
    if article is None:
        return CommonResult(code=500, msg='文章不存在')
    # 深拷贝tags,然后清除tags，防止添加时使用到传入的id集合
    tag_ids = copy.deepcopy(data.get('tags'))
    data.pop('tags')
    # 更新信息
    article.title = data.get('title')
    article.description = data.get('description')
    article.content = data.get('content')
    article.has_type = data.get('has_type')
    article.category_id = data.get('category_id')
    # 重新设置标签信息
    article.tags = [Tag.query.get(tag_id) for tag_id in tag_ids]
    # 提交更新信息
    db.session.commit()
    return CommonResult(data=data, msg='修改成功')


# 删除记录
@admin_article.get('/delete/<int:article_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def delete(article_id):
    # 查询是否存在
    article = Article.query.get(article_id)
    if article is None:
        return CommonResult(code=500, msg='删除的文章不存在')
    # 删除记录
    db.session.delete(article)
    db.session.commit()
    return CommonResult(msg='删除成功')
